package org.example.utils;

import org.apache.commons.lang.StringUtils;
import org.example.constants.CommonConstants;
import org.example.model.Browser;
import org.example.model.Device;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class GlobalUtils {

    /**
     * 启动浏览器驱动，暂时只支持Chrome浏览器
     * @param userDataPath
     * @return
     */
    public static WebDriver startDriver(String userDataPath) {
        // 谷歌驱动
        ChromeOptions options = new ChromeOptions();
        // 火狐驱动
        // FirefoxOptions options = new FirefoxOptions();
        // Edge驱动
        // EdgeOptions options = new EdgeOptions();
        // 谷歌允许所有请求
        options.addArguments("--remote-allow-origins=*");
        // 后台运行
        // options.addArguments("--headless");
        // 提高截屏分辨率
        options.addArguments("--force-device-scale-factor=1");
        if (StringUtils.isNotEmpty(userDataPath)) {
            // 通过 chrome://version/ 查看 user-data 位置，要去掉default，关掉目前的Chrome才可
            options.addArguments("user-data-dir=" + userDataPath);
        }

        WebDriver webDriver;
        try {
            // 谷歌
            webDriver = new ChromeDriver(options);
            // 火狐
            // webDriver = new FirefoxDriver(options);
            // Edge
            // webDriver = new EdgeDriver(options);
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("浏览器已开启，请关闭原有浏览器后再启动程序！");
            return null;
        }

        // 启动需要打开的网页
        webDriver.get(CommonConstants.URL);
        webDriver.manage().window().maximize();
        GlobalUtils.sleep(2000);
        return webDriver;
    }

    public static void init(WebDriver webDriver, Browser browser, Device device) {
        browser = BrowserUtils.initBrowser(webDriver);
        device= DeviceUtils.initDeviceInfo(webDriver);
    }

    /**
     * 打开一个新标签页
     * @param webDriver
     */
    public static void openNewTab(WebDriver webDriver) {
        ((JavascriptExecutor)webDriver).executeScript("window.open('"+CommonConstants.URL+"','_blank');");
    }

    /**
     * 打开一个新标签页
     * @param webDriver
     */
    public static void openNewTab(WebDriver webDriver, String url) {
        ((JavascriptExecutor)webDriver).executeScript("window.open('"+url+"','_blank');");
    }

    /**
     * 获取设备列表URL链接
     * @param webDriver
     */
    public static List<String> findDeviceList(WebDriver webDriver) {
        List<String> deviceList = new ArrayList<>();
        // webDriver.findElement(By.cssSelector("body > header > button > svg"));
        // webDriver.findElement(By.className("atm_66_nqa18y atm_84_ftgil2 atm_bb_idpfg4 atm_9s_116y0ak atm_ar_vrvcex atm_h_1h6ojuz atm_fc_1h6ojuz atm_2d_1j28jx2 atm_7l_ukqhw6 atm_4b_1j28jx2 atm_6h_t94yts atm_e2_viql5b atm_lk_idpfg4 atm_ll_idpfg4 atm_5j_14y27yu atm_c8_1j6vyhq atm_rd_glywfm atm_9j_73adwj atm_uq_us0x7g atm_ui_1bwjh7f atm_uv_1ytfnp0 atm_1y17hwk_16dy53r atm_18uqgji_1hd7qks atm_vy_viql5b atm_gz_4h84z3 atm_1r_cj8er add"));
        WebElement switchEle = webDriver.findElement(By.xpath("/html/body/header/button"));
        if (switchEle != null) {
            switchEle.click();
            GlobalUtils.sleep(3000);
        }
        WebElement availableListParent = webDriver.findElement(By.xpath("/html/body/div[2]/div/div/div[2]/div"));
        if (availableListParent != null) {
            List<WebElement> deviceEleList = availableListParent.findElements(By.tagName("a"));
            deviceList = deviceEleList.stream().map(device -> device.getAttribute("href")).filter(device -> StringUtils.isNotEmpty(device)).collect(Collectors.toList());
        }
        return deviceList;
    }
    /**
     * 线程休眠
     * @param millis 毫秒
     */
    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 随机字符串
     * @return
     */
    public static String randomStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 输出日志
     * @param str
     */
    public static void logi(String str) {
        System.out.println(str);
    }

    /**
     * 滑动
     * @param webDriver
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @param duration
     */
    public static void swipe(WebDriver webDriver, Device device, int x1, int y1, int x2, int y2, int duration) {
        Actions actions = new Actions(webDriver);
        actions.moveToLocation(device.getOffsetX() + x1, device.getOffsetY() + y1)
                .clickAndHold()
                .moveToLocation(device.getOffsetX() + x2,device.getOffsetY() + y2)
                .release().perform();
    }

    /**
     * 点击
     * @param webDriver
     * @param x
     * @param y
     */
    public static void click(WebDriver webDriver, Device device, int x, int y) {
        Actions actions = new Actions(webDriver);
        int clickX = device.getOffsetX() + x + CommonConstants.offsetX;
        int clickY = device.getOffsetY() + y + CommonConstants.offsetY;
        /*// int clickX = 775;
        // int clickY = 480;
        int x1 = clickX;
        int y1 = clickY + 200;
        int x2 = clickX - 200;
        int y2 = clickY + 700;*/
        System.out.println("device.getOffsetX() == " + device.getOffsetX() + ",device.getOffsetY() == " + device.getOffsetY());
        System.out.println("x == " + x + ",y == " + y);
        System.out.println("clickX == " + clickX + ",clickY == " + clickY);

        // actions.moveToLocation(clickX, clickY).click().build().perform();
        actions.moveToLocation(clickX, clickY).click()
                .build().perform();
        /*GlobalUtils.sleep(2000);
        actions.moveToLocation(device.getOffsetX() + x1, device.getOffsetY() + y1)
                .clickAndHold()
                .moveToLocation(device.getOffsetX() + x2,device.getOffsetY() + y2)
                .release().perform();*/
    }

    /**
     * 返回主页
     * @param webDriver
     * @return
     */
    public static boolean home(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[8]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }

    /**
     * 返回
     * @param webDriver
     * @return
     */
    public static boolean back(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[7]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }

    /**
     * 显示最近任务
     * @param webDriver
     * @return
     */
    public static boolean recents(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[9]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }

    /**
     * 电源键
     * @param webDriver
     * @return
     */
    public static boolean power(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[14]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }

    /**
     * 音量加
     * @param webDriver
     * @return
     */
    public static boolean volumeUp(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[11]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }

    /**
     * 音量减
     * @param webDriver
     * @return
     */
    public static boolean volumeDown(WebDriver webDriver) {
        final WebElement ele = webDriver.findElement(By.xpath("//*[@id=\"content\"]/div[2]/div[2]/div/div/div[3]/div/div/div[12]"));
        if (ele != null) {
            ele.click();
            return true;
        }
        return false;
    }
}
